package com.controller;


import com.alibaba.fastjson.JSON;
import com.doMain.TableVO;
import com.pojo.SysMenu;
import com.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/sysMenu")
public class SysMenuController {

    @Autowired
    private SysMenuService service;

    @GetMapping("/toList")
    public String toList(){
        return "menuList";
    }

    @GetMapping(value = "/list",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String list(Integer page,Integer limit,String menuName,String menuType){
        List<SysMenu> list=service.list(page,limit,menuName,menuType);
        int count=service.count(menuName,menuType);
        TableVO tableVO = new TableVO(0, count, list, "");
        String s = JSON.toJSONString(tableVO);
        return s;
    }

    @GetMapping("/toAdd")
    public String toAdd(){
        return "menuAdd";
    }

    @PostMapping(value = "/add",produces = "application/json;charset=utf-8")
    public String add(SysMenu menu, Model model) {
        int add=service.add(menu);
        if (add>0){
            return "redirect:toList";
        }
        model.addAttribute("errorMsg","新增失败");
        return "menuAdd";
    }

    @GetMapping("/toEdit/{menuId}")
    public String toEdit(@PathVariable("menuId") Integer id, Model model){
        SysMenu sysMenu=service.view(id);
        model.addAttribute("menu",sysMenu);
        return "menuEdit";
    }

    @GetMapping(value = "/edit",produces = "application/json;charset=utf-8")
    @ResponseBody
    public void  edit(SysMenu menu,HttpServletResponse response) throws IOException {
        int edit=service.edit(menu);
        if (edit>0){
            response.getWriter().print("1");
        }
        response.getWriter().print("0");

    }


    @GetMapping(value = "/delete/{menuId}")
    @ResponseBody
    public void  del(@PathVariable("menuId") Integer id, HttpServletResponse response) throws IOException {
            int edit=service.del(id);
        if (edit>0){
            response.getWriter().print("1");
        }else {
            response.getWriter().print("0");
        }
    }

    @GetMapping("/view/{menuId}")
    public String view(@PathVariable("menuId") Integer id,Model model){
        SysMenu menu=service.view(id);
        model.addAttribute("menu",menu);
        return  "menuView";
    }

}
